package com.bbz.core.lambda.java8.Chapter_7_parallel;

import java.util.concurrent.atomic.LongAccumulator;
import java.util.function.Function;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

/**
 * JAVA8 实战并行数据处理与性能
 */
public class ParallelData {

    /**
     * 测量对前n个自然数求和的函数的性能
     * @param adder
     * @param n
     * @return
     */
    public static long measureSumPerf(Function<Long, Long> adder, long n) {
        long fastest = Long.MAX_VALUE;
        for (int i = 0; i < 10; i++) {
            long start = System.nanoTime();
            long sum = adder.apply(n);
            long duration = (System.nanoTime() - start) / 1_000_000;
            System.out.println("Result: " + sum);
            if (duration < fastest) fastest = duration;
        }
        return fastest;
    }

    public static  void main(String args[]){
        System.out.println("顺序流处理时间:" +
                measureSumPerf(ParallelStreams::sequentialSum, 10_000_000) + " ms");
        System.out.println("并行流处理时间:" +
                measureSumPerf(ParallelStreams::parallelSum, 10_000_000) + " ms");
        System.out.println("传统方式处理时间:" +
                measureSumPerf(ParallelStreams::iterativeSum, 10_000_000) + " ms");
        System.out.println("顺序流RangedSum处理时间:" +
                measureSumPerf(ParallelStreams::rangedSum, 10_000_000) + " ms");
        System.out.println("并行流RangedSum处理时间:" +
                measureSumPerf(ParallelStreams::parallelRangedSum, 10_000_000) + " ms");
        //线程不安全的并行流，导致的原因是因为total += value 不是原子操作，使用并行流应该避免有共享状态
        System.out.println("并行流sideEffectSum处理时间:" +
                measureSumPerf(ParallelStreams::sideEffectSum, 10_000_000) + " ms");
    }




}
